import { ExclamationCircleFilled } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, message, Modal } from 'antd';
import React, { useRef, useState } from 'react';
import RobotProductForm from './components/RobotProductForm';
import { productsTaskList, saveProductTask } from './service';
const { confirm } = Modal;

const fillTypes = [
  { label: '全部', value: 3 },
  { label: '商品', value: 1 },
  { label: '口令', value: 2 },
];
const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [hotProductVisible, handleHotProductVisible] = useState<boolean>(false);
  const [products, setProducts] = useState<any>({});
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const showDeleteConfirm = (record: any) => {
    confirm({
      title: '你确定要删除当前关键词?',
      icon: <ExclamationCircleFilled />,
      content: record.keyword,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        message.info('删除中');
        const rsp = await saveProductTask({ ...record, type: 1 });
        if (rsp.code === 'SUCCESS') {
          message.success('删除成功');
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  const columns: ProColumns<any>[] = [
    {
      title: '关键词',
      dataIndex: 'keyword',
      copyable: true,
    },
    {
      title: '分类',
      dataIndex: 'cate',
      hideInSearch: true,
    },
    {
      title: '佣金比例',
      dataIndex: 'rate',
      hideInSearch: true,
      sorter: (a, b) => a.rate - b.rate,
      render: (amount) => {
        // 使用 toFixed(2) 保留两位小数
        return parseFloat(amount) + '%';
      },
    },
    {
      title: '抓取类型',
      dataIndex: 'type',
      valueType: 'select',
      request: async () => {
        return fillTypes;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: { text: '未抓取', status: 'Default' },
        1: { text: '抓取中', status: 'Processing' },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'startTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 80,
      align: 'right',
      fixed: 'right',
      render: (text, record) => [
        <a
          key="editable"
          onClick={async () => {
            setProducts({ ...record });
            handleHotProductVisible(true);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={async () => {
            await showDeleteConfirm(record);
          }}
        >
          删除
        </a>,
        <a
          key="delete"
          onClick={async () => {
            message.info('更新操作中');
            const rsp = await saveProductTask({
              ...record,
              status: record.status === 1 ? 0 : 1,
              type: 2,
            });
            if (rsp.code === 'SUCCESS') {
              message.success('更新成功');
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
        >
          {record.status === 1 ? '下架' : '上架'}
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={'全部商品'}
        actionRef={actionRef}
        rowClassName={(record: any) => {
          if (record.proRate === 0 && record.amount !== 0) {
            return 'completed-row'; // 为状态为“已完成”的行添加样式
          }
          return '';
        }}
        rowKey="key"
        toolBarRender={() => [
          <Button
            key="23"
            type="primary"
            onClick={() => {
              handleHotProductVisible(true);
              setProducts({});
            }}
          >
            添加商品
          </Button>,
        ]}
        search={{
          defaultCollapsed: false,
        }}
        request={async (params: any) => {
          const rsp = await productsTaskList(params);
          if (rsp.code === 'SUCCESS') {
            return {
              data: rsp.data,
              total: rsp.data.length,
            };
          }
        }}
        columns={columns}
      />

      <RobotProductForm
        visible={hotProductVisible}
        onSubmit={async (value) => {
          const rsp = await saveProductTask(value);
          if (rsp.code === 'SUCCESS') {
            handleHotProductVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleHotProductVisible(false);
        }}
        values={products} // 初始值
      />
    </PageContainer>
  );
};
export default TableList;
